package com.luoran.bartalks.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.luoran.bartalks.annotation.OperationLog;
import com.luoran.bartalks.core.AppUser;
import com.luoran.bartalks.entity.biz.UserInfo;
import com.luoran.bartalks.service.IBtOperationLogService;
import com.luoran.bartalks.utils.EnumOperationType;
/**
 * 
 * @ClassName: OperationLogAspect 
 * @Description: 切面增强类：APP操作自动加操作记录
 * @author: M1nG
 * @date: 2019年2月22日 上午10:32:56
 */
@Aspect
@Component
public class OperationLogAspect {
	@Autowired
	private IBtOperationLogService operationLogService;

	@Pointcut("@annotation(com.luoran.bartalks.annotation.OperationLog)")
	public void record(OperationLog operationLog) {
	}

	@Around("@annotation(operationLog)")
	public Object Interceptor(ProceedingJoinPoint pjp, OperationLog operationLog) throws Throwable {
		Object result = null;
		if (operationLog.value() == EnumOperationType.LOGOUT) {
			operationLogService.saveOperationRecord(AppUser.get().getId(), AppUser.get().getAlias(),
					AppUser.get().getCompanyId(), operationLog.value().getValue());
			result = pjp.proceed();
		} else {
			result = pjp.proceed();
			JSONObject resultObject = JSON.parseObject(result.toString());
			Boolean b = resultObject.getBoolean("state");
			if (b) {
				if (operationLog.value() == EnumOperationType.LOGIN) {
					UserInfo user = resultObject.getObject("userInfo", UserInfo.class);
					operationLogService.saveOperationRecord(user.getId(), user.getNick(),
							user.getCompanyId(), operationLog.value().getValue());
				} else {
					operationLogService.saveOperationRecord(AppUser.get().getId(), AppUser.get().getAlias(),
							AppUser.get().getCompanyId(), operationLog.value().getValue());
				} 

			}
		}
		return result;
	}

}
